/*
 *date: 2016-2-20
 *name: king.pc.js
 *version: 1.3
 *designBy: henger.wang
 */
;(function($){
	var king = {
		isEmpty: function(info){
			if(info==null||info==undefined||(""+info)==""){
				return true;
			}
			return false;
		},
		//可配参数{title:'',html:'',btns:[],init:fun}
		dialog:function(data){
			var _this = this;
			var boxId = "lktbox"+(Math.random()+'').substring(2,4);
			var closeId = "close"+boxId;
			var hideBox = function(){
				$("#"+boxId).remove();
			}
			var data = {
				"title":!data.title?"提示":data.title,
				"html":!data.html?"没有内容":data.html,
				"btns":!data.btns?[{"name":"确定"}]:data.btns,
				"init":data.init
			};
			var boxHtml = '<div class="lkt_box" id="'+boxId+'"><div class="lkt_cover"></div><div class="lkt_box_wrap"><div class="lkt_box_in"><div class="lkt_box_close"><span id="'+closeId+'">&times;</span></div><div class="lkt_box_title">'+data.title+'</div><div class="lkt_box_cont">'+data.html+'</div><div class="lkt_box_btns"></div></div><div class="lkt_box_border"></div></div>';
			$("#"+boxId).remove();
			$("body").append(boxHtml);
			$("#"+closeId).on("click",function(){
				hideBox();
			});
			$.each(data.btns,function(i){
				$('<span>'+data.btns[i].name+'</span>').appendTo("#"+boxId+" .lkt_box_btns").on("click",function(){
					data.btns[i].ev?(data.btns[i].ev({"hideBox":function(){hideBox()}})!==false&&hideBox()):hideBox();
				});
			});
			var boxIn = $("#"+boxId+" .lkt_box_wrap");
			boxIn.width();//修复ie8获取不到宽度的bug
			var boxWidth = boxIn.width();
			var boxHeight = boxIn.height();
			boxIn.css({"width":boxWidth+"px","margin-left":(-boxWidth/2)+"px","margin-top":(-boxHeight/2)+"px"});
			if(data.init)data.init(boxIn);
		},
		alert: function(data, callback){
			var JSON = {};
			if($.isArray(data)){
				if(data.length==3){
					var JSON = {"title":data[0],"content":data[1],"ok":data[2]||'确认'}
				}else{
					var JSON = {"title":"温馨提示","content":data[0],"ok":data[1]||'确认'}
				}			
			}else{
				var JSON = {"title":"温馨提示","content":data,"ok":"确定"}
			}
			this.dialog({
				"title":JSON.title,
				"html":JSON.content,
				"btns":[{"name":JSON.ok,ev:callback}]
			});
		},
		confirm: function(data,callback1,callback2){
			var JSON = {};
			if($.isArray(data)){
				if(data.length==3){
					JSON = {"title":"温馨提示","content":data[0],"ok":data[1]||'确认',"cancel":data[2]||'取消'}
				}else if(data.length==4){
					JSON = {"title":data[0],"content":data[1],"ok":data[2]||'确认',"cancel":data[3]||'取消'}
				}
			}else{
				JSON = {"title":"温馨提示","content":data,"ok":"确定","cancel":"取消"}
			}
			this.dialog({
				"title":JSON.title,
				"html":JSON.content,
				"btns":[{"name":JSON.ok,ev:callback1},{"name":JSON.cancel,ev:callback2}]
			});
			$(".lkt_box_btns>span:eq(1)").addClass("cancel");
		},
		//type:{0:error,1|空:success}
		tips: function(str,type){
			if(!this.isEmpty(str)){
				var boxId = "box1990"+(Math.random()+'').substring(2,4);
				var closeId = "close"+boxId;
				var html = '<div class="lkt_tips" id="'+boxId+'">'+str+'<span class="lkt_tips_close" id="'+closeId+'">&times;</span></div>';
				$("body").append(html);
				var tclass = type==0?"error":"success";
				var tipsObj = $("#"+boxId);
				tipsObj.addClass(tclass).fadeIn(200);
				$("#"+closeId).click(function(){
					tipsObj.remove();
				});
				setTimeout(function(){
					tipsObj.fadeOut(200).delay(200,function(){
						$(this).remove();
					});
				},2000);
			}else{
				return false;
			}
		},
		getLocalImage: function(input,callback){
			if(input instanceof HTMLElement){
				var file = input.files[0];
				var reg = /image\/jpg|png|gif|jpeg/;
				if(!file){
					this.tips("请选择图片");
					return false;
				}else if(!reg.test(file.type)){
					this.tips("可选图片格式为png、jpg、gif");
					input.value = '';
					return false;
				}else{
					var reader = new FileReader();
					reader.readAsDataURL(file);
					reader.onload = function(e){
						if(typeof callback === "function"){
							callback({"name":file.name,"type":file.type,"size":file.size,"src":this.result});
						}
					}
				}
			}else{
				this.tips("input参数错误");
			}
		},
		compressImage: function(src, length, callback){
			var lenth = parseInt(lenth);
			var image = new Image();
			image.src = src;
			image.onload = function() {
				var width = image.width;
				var height = image.height;
				var aspect = width/height;
				if(width>=length){
					var w = length;
					var h = w/aspect;
				}else if(height>=length){
					var h = length;
					var w = h*aspect;
				}else{
					return false;
				}
				var canvas = $('<canvas width="'+w+'" height="'+h+'"></canvas>').appendTo("body").get(0);
				var context = canvas.getContext('2d');
				context.drawImage(image, 0, 0, w, h);
				var imgData = canvas.toDataURL("image/png");
				if($.isFunction(callback)){
					document.body.removeChild(canvas);
					callback(imgData);
				}
			};
		},
		viewImage: function(index, srcs){
			var boxId = "box1990"+(Math.random()+'').substring(2,4);
			$(".lkt_image_view").size()==0&&$('<div class="lkt_image_view load" id="'+boxId+'"><div class="prev icon"></div><div class="next icon"></div><div class="close icon icon-close"></div><div class="image-vert"></div></div>').appendTo("body");
			var box = $("#"+boxId)
			var prev = box.children(".prev");
			var next = box.children(".next");
			var close = box.children(".close");
			var img = new Image();
			img.onload = function(){
				box.append(img).removeClass("load");
			}
			img.src = srcs[index];
			prev.on("click", function(){
				if(index>0){
					index--;
					$(img).attr("src", srcs[index]);
				}
			});
			next.on("click", function(){
				if(index<srcs.length-1){
					index++;
					$(img).attr("src", srcs[index]);
				}
			});
			close.on("click", function(){
				box.remove();
			});
		},
		delay: function(t){
			var t = t||0;
			var t1 = Number(new Date());
			var t2 = Number(new Date()); 
			while(t2-t1<t){
				t2 = Number(new Date()); 
			}
		},
		doAjax: function(data){
			var _this = this;
			_this.isEmpty(data.data)&&(data.data = {});
			data.data._csrf = $('meta[name="csrf-token"]').attr("content");
			$.ajax({
				url: data.url,
				type: data.type||"get",
				dataType: data.dataType||"json",
				data: data.data,
				success: data.success,
				error: data.error||function(){
					_this.alert("网络连接失败")
				}
			});
		},
		go: function(url){
			if(typeof url == "string"){
				window.location.href = url
			}else if(typeof url == "number"){
				window.history.go(url)
			}
		},
		loginPopup: function(getLoginUrl, loginUrl, codeUrl, callback){
			//需要页面里全局变量加载登录地址pcLoginUrl
			$.post(getLoginUrl, function(data){
				if(data.html){
					$("body").append(data.html);
					//然后做下面的事情
					var login = $("#loginPopup");
					var loginBox = login.children(".login-box");
					var submitBtn = login.find(".login-submit");
					var loginName = login.find("[name='login_name']");
					var password = login.find("[name='login_password']");
					var codeWrap = login.find(".login-code");
					var code = codeWrap.find("[name='login_yzm']");
					var codeImg = codeWrap.children(".login-code-reget");
					var error = login.find(".login-error");
					var errorCounts = 0;
					login.on("click", function(){
						login.remove();
					});
					loginBox.on("click", function(e){
						e.stopPropagation();
					});
					loginBox.css("margin-top", -loginBox.innerHeight()/2+"px");
					codeImg.on("click", function(){
						$(this).children("img").attr("src", codeUrl)
					});
					submitBtn.on("click", function(){
						if(loginName.val()==""){
							error.text("用户名不能为空");
						}else if(password.val()==""){
							error.text("密码不能为空");
						}else if(codeWrap.is(":visible")&&code.val()==""){
							error.text("请输入验证码");
						}else{
							$.doAjax({
								url: loginUrl,
								data: $("#baseform").serialize(),
								type: "post",
								dataType: "json",
								success: function(data){
									if(data.flag == 0){
										error.text('');
										$.go(0);
									}else{
										codeImg.click();
										error.text(data.desc);
										errorCounts==2&&codeWrap.show();
										errorCounts++;
									}
									$.isFunction(callback)&&callback(data);
								}
							});
							return false;
						}
						errorCounts==2&&codeWrap.show();
						errorCounts++;
					});
				}else{
					$.alert("无法登录");
				}
			})
		}
	}
	$.extend(king);	
})(jQuery);
/**
 *方法名称：秒钟倒计时
 *参数：{obj:显示秒数的对象;t:总秒数;callback:结束后的回调函数}
 */
function rTime(obj, t, callback) {
	if(typeof t != "number" && typeof callback != "function"){
		console.info("dtime:参数类型出错!");
		return false;
	}
    if(t > 0){
		$(obj).text(t);
        t--;
		setTimeout(function(){
			rTime(obj,t,callback);
		},1000);
    }else if(typeof callback == "function"){
		callback();
	}
}
/**
 *方法名称：日期倒计时
 *参数：{obj:显示日期的对象;t:总日期;callback:结束后的回调}
 */
function rDate(obj, t, callback){
	if(typeof t != "number" && typeof callback != "function"){
		console.info("dtime:参数类型出错!");
		return false;
	}
    if(t > 0) {
		$(obj).text(timeFormat(t));
        t --;
		setTimeout(function(){
			rDate(obj,t);
		},1000);
    }else if(typeof callback == "function"){
		callback();
	}
}
/**
 *方法名称：时间格式化
 *参数:{t:时间}
 */
function timeFormat(t){
	t = parseInt(t);
	var d = parseInt(t/(24*3600));
	var h = parseInt((t-(d*24*3600))/3600);
	h = h<10?"0"+h:h;
	var m = parseInt((t-(d*24*3600)-h*3600)/60);
	m = m<10?"0"+m:m;
	var s = parseInt(t-(d*24*3600)-h*3600-m*60);
	s = s<10?"0"+s:s;
	return (d==0?"":d+"天 ")+h+":"+m+":"+s;
}

//滚动到指定元素位置执行回调
function whileToObject(o, callback1, callback2){
	if(typeof o!="object")return false;
	var height = $(window).height();
	$(window).scroll(function(){
		var pos = o.offset().top+o.height();
		if($(window).scrollTop()+height >= pos){
			$.isFunction(callback1)&&callback1();
		}else{
			$.isFunction(callback2)&&callback2();
		}
	}).trigger("scroll");
	$(window).on("resize", function(){
		height = $(window).height();
	})
}
//滚动到指定位置执行回调
function whileToPosition(pos, callback1, callback2){
	var height = $(window).height();
	$(window).scroll(function(){
		if($(window).scrollTop()+height >= pos){
			$.isFunction(callback1)&&callback1();
		}else{
			$.isFunction(callback2)&&callback2();
		}
	}).trigger("scroll");
	$(window).on("resize", function(){
		height = $(window).height();
	})
}
//滚到底部
function whileToEnd(callback){
	$(window).scroll(function(){
		if($(window).scrollTop()>=$(document).height()-$(window).height()){
			$.isFunction(callback)&&callback();
		}
	});
}
//文字闪色
function switchColor(o, c){
	o.css("color", c[0]);
	c.reverse();
	setTimeout(function(){
		switchColor(o, c)
	}, 600);
}
//滚动到顶部
function addGotop(){
	var gotop = $('<div class="gotop"><i class="icon icon-arrow-up5"></i></div>');
	gotop.appendTo("body").on("click", function(){
		$("html,body").animate({scrollTop:0},200)
	});
	whileToPosition($(window).height()+1,function(){
		gotop.fadeIn();
	}, function(){
		gotop.fadeOut();
	});
}

